package repository

import (
	"yak.admin/src/entity"
	"yak.admin/src/service"
	"yak.admin/src/util"
)

type DeviceReportRepository struct {
}

func (repository *DeviceReportRepository) StatusLabels() map[int]string {
	return map[int]string{
		util.PendingStatus: "待审核",
		util.FollowStatus:  "已关注",
		util.IgnoreStatus:  "已忽略",
	}
}

func (repository *DeviceReportRepository) DeviceDescLabels() map[int]string {
	var riskDesc []*entity.DeviceRiskDesc
	db := util.GetMysqlPool().Handler()
	if db.Find(&riskDesc).RecordNotFound() {
		return map[int]string{}
	}
	labels := make(map[int]string, len(riskDesc))
	for _, m := range riskDesc {
		labels[m.Id] = m.Name
	}
	return labels
}

func (repository *DeviceReportRepository) DeviceAnalysisLabels() map[int]string {
	var riskAnalysis []*entity.DeviceRiskAnalysis
	db := util.GetMysqlPool().Handler()
	if db.Find(&riskAnalysis).RecordNotFound() {
		return map[int]string{}
	}
	labels := make(map[int]string, len(riskAnalysis))
	for _, m := range riskAnalysis {
		labels[m.Id] = m.Name
	}
	return labels
}

func (repository *DeviceReportRepository) FindReport(id uint) map[string]interface{} {
	report := entity.DeviceReport{}
	reader := new(service.ReaderQuery).CreateModelQuery(&report).
		WithEQ("id", id).WithPreloads([]string{"RiskDescAnnexes", "RiskAnalysisAnnexes", "Admin"})
	reader.One(&report)
	riskDescLabels := repository.DeviceDescLabels()
	riskAnalysisLabels := repository.DeviceAnalysisLabels()
	return reader.Viewlist(&report, func(item interface{}) map[string]interface{} {
		m := item.(*entity.DeviceReport)
		DescAnnexes := m.RiskDescAnnexes
		riskDescFnt := func() map[int][]interface{} {
			if len(DescAnnexes) > 0 {
				mm := map[int][]interface{}{}
				for _, annex := range DescAnnexes {
					if annex.AnnexType == 1 {
						annex.Src = util.GetImage(annex.Src)
					}
					mm[annex.Type] = append(mm[annex.Type], annex)
				}
				return mm
			}
			return map[int][]interface{}{}
		}

		AnalysisAnnexes := m.RiskAnalysisAnnexes
		riskAnalysisFnt := func() map[int][]interface{} {
			if len(AnalysisAnnexes) > 0 {
				mm := map[int][]interface{}{}
				for _, annex := range AnalysisAnnexes {
					if annex.AnnexType == 1 {
						annex.Src = util.GetImage(annex.Src)
					}
					mm[annex.Type] = append(mm[annex.Type], annex)
				}
				return mm
			}
			return map[int][]interface{}{}
		}

		return map[string]interface{}{
			"number": m.Number,
			"reported_at": reader.AsDatetime(m.ReportedAt),
			"company_name": m.CompanyName,
			"produce_name": m.ProduceName,
			"produce_number": m.ProduceNumber,
			"produce_id": m.ProduceId,
			"risk_desc": riskDescFnt(),
			"desc_labels": riskDescLabels,
			"status": m.Status,
			"comment": m.Comment,
			"risk_analysis": riskAnalysisFnt(),
			"analysis_labels": riskAnalysisLabels,
			"admin_avatar": util.GetImage(m.Admin.Avatar),
		}
	})
}